package com.qf.io.serverSocket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/16
 */
public class ServerSocketDemo {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //创建一个socket
            serverSocket = new ServerSocket(8080);
            //等待客户端连接
//            while (true){
                Socket socket = serverSocket.accept();  //这个方法是个阻塞方法
                System.out.println("有新客户端连接");
                InputStream inputStream = socket.getInputStream();
                Scanner scanner = new Scanner(inputStream);
                StringBuffer stringBuffer = new StringBuffer();
                while (scanner.hasNextLine()){
                    stringBuffer.append(scanner.nextLine());
                }
                System.out.println("服务端读取的内容是:"+stringBuffer.toString());
                stringBuffer.append("服务端");
                socket.getOutputStream().write(stringBuffer.toString().getBytes("utf-8"));

//            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
